<template>
  <div class="course_box" v-loading="loading">
    <div class="course_addbtn">
      <el-button icon="plus" @click="openAddDialog()" type="primary">
        选择课程
      </el-button>
      <el-button icon="Minus" @click="withdrawCourse()" type="danger">
        批量退课
      </el-button>
      <span style="margin-left: 12px">学期：</span>
      <el-select
        v-model="coursePageParmas.semesterId"
        placeholder="请选择学期"
        clearable
        filterable
        @change="getCourseInfoPage()"
      >
        <el-option
          v-for="item in semesterOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </div>
    <el-table
      :data="courseDatas"
      border
      :header-row-style="{ color: '#232324', fontWeight: 'bold' }"
      @selection-change="handleSelectionChange1"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column
        align="center"
        type="index"
        :index="indexMethod"
        label="序号"
        width="60"
      />
      <el-table-column
        align="center"
        label="课程名称"
        min-width="120"
        prop="courseName"
      />
      <el-table-column
        align="center"
        label="课程代码"
        min-width="120"
        prop="courseCode"
      />
      <el-table-column align="center" label="教师" min-width="120">
        <template #default="scope">
          <el-tag>{{ scope.row.teacher.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="学分"
        min-width="120"
        prop="credit"
      />
      <el-table-column
        align="center"
        label="开设学院"
        min-width="120"
        prop="department"
      />
      <el-table-column
        align="center"
        label="已选人数"
        min-width="180"
        prop="num"
      />
      <el-table-column
        align="center"
        label="最大可选人数"
        min-width="180"
        prop="maxNum"
      />
      <el-table-column
        align="center"
        label="选课时间"
        min-width="180"
        prop="createTime"
      />
      <el-table-column align="center" fixed="right" label="操作" width="300">
        <template #default="scope">
          <el-popconfirm
            :icon="InfoFilled"
            icon-color="#626AEF"
            width="180"
            title="是否退选该课程?"
            @confirm="withdrawCourseById(scope.row.enrollmentId)"
          >
            <template #reference>
              <el-button type="primary" link icon="CircleCloseFilled">
                退课
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 12px"
      v-model:current-page="coursePageParmas.pageNum"
      v-model:page-size="coursePageParmas.pageSize"
      :page-sizes="[10, 20, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="dialogFormVisible"
      :title="dialogTitle"
      style="min-width: 820px"
      width="75%"
    >
      <span>学期：</span>
      <el-select
        v-model="selectedSemesterId"
        placeholder="请选择学期"
        @change="getCourseOptions(selectedSemesterId)"
      >
        <el-option
          v-for="item in semesterOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-table
        :data="courseOptions"
        border
        :header-row-style="{ color: '#232324', fontWeight: 'bold' }"
        @selection-change="handleSelectionChange"
        style="margin-top: 24px"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          align="center"
          label="课程名称"
          min-width="120"
          prop="courseName"
        />
        <el-table-column
          align="center"
          label="课程代码"
          min-width="120"
          prop="courseCode"
        />
        <el-table-column align="center" label="教师" min-width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.teacher.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="学分"
          min-width="120"
          prop="credit"
        />
        <el-table-column
          align="center"
          label="开设学院"
          min-width="120"
          prop="department"
        />
        <el-table-column
          align="center"
          label="已选人数"
          min-width="180"
          prop="num"
        />
        <el-table-column
          align="center"
          label="最大可选人数"
          min-width="180"
          prop="maxNum"
        />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="formConfirm()">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import {
  reqAddEnrollmentByStu,
  reqDeleteEnrollmentByStu,
  reqGetCourseByStu,
  reqGetOptionalCourseByStu,
} from '@/api/course'
import {
  CoursePageQuery,
  CourseType,
  SelectCourseParams,
  WithdrawCourseParams,
} from '@/api/course/type'
import { reqGetSemesterOption } from '@/api/semester'
import { OptionType } from '@/api/user/type'
import useUserStore from '@/store/modules/user'

onMounted(async () => {
  await getCourseInfoPage()
  await getSemesterOption()
})

const dialogFormVisible = ref<boolean>(false)
const coursePageParmas: CoursePageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
})
const courseDatas = ref<CourseType[]>()
const total = ref(0)
const loading = ref(false)
const semesterOptions = ref<OptionType[]>([])
const courseOptions = ref<CourseType[]>([])
const selectedSemesterId = ref<number>(0)
const selectedCourseOptions = ref<CourseType[]>([])
const withdrawedCourseOptions = ref<CourseType[]>([])
const userStore = useUserStore()

const indexMethod = (index: number) => {
  return index + (coursePageParmas.pageNum - 1) * coursePageParmas.pageSize + 1
}

// 添加菜单方法，id为 0则为添加根菜单
const dialogTitle = ref('选课')

const getCourseInfoPage = async () => {
  loading.value = true
  try {
    const { data } = await reqGetCourseByStu(coursePageParmas)
    courseDatas.value = data.list
    total.value = data.total
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}

const getSemesterOption = async () => {
  try {
    const { data } = await reqGetSemesterOption()
    semesterOptions.value = data
    selectedSemesterId.value = data[0].id
    getCourseOptions(selectedSemesterId.value)
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  }
}

const getCourseOptions = async (semesterId: number) => {
  try {
    const { data } = await reqGetOptionalCourseByStu(semesterId)
    courseOptions.value = data
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  }
}

const withdrawCourseById = async (id: number) => {
  let data: WithdrawCourseParams = {
    enrollmentIds: [],
  }
  data.enrollmentIds.push(id)
  try {
    const { message } = await reqDeleteEnrollmentByStu(data)
    ElMessage.success(message)
    await getCourseInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const withdrawCourse = async () => {
  let data: WithdrawCourseParams = {
    enrollmentIds: [],
  }
  withdrawedCourseOptions.value.forEach((item) => {
    data.enrollmentIds.push(item.enrollmentId)
  })
  try {
    const { message } = await reqDeleteEnrollmentByStu(data)
    ElMessage.success(message)
    await getCourseInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const selectCourse = async () => {
  let data: SelectCourseParams = {
    studentId: Number(userStore.userInfo.username),
    courseIds: [],
  }
  selectedCourseOptions.value.forEach((item) => {
    data.courseIds.push(item.courseId)
  })
  try {
    const { message } = await reqAddEnrollmentByStu(data)
    ElMessage.success(message)
    await getCourseInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const formConfirm = async () => {
  if (selectedCourseOptions.value.length === 0) {
    ElMessage.error('未选择课程！')
    return
  }
  selectCourse()
  dialogFormVisible.value = false
}

const openAddDialog = () => {
  dialogFormVisible.value = true
}

const handleSelectionChange = (val: CourseType[]) => {
  selectedCourseOptions.value = val
}

const handleSelectionChange1 = (val: CourseType[]) => {
  withdrawedCourseOptions.value = val
}

const handleSizeChange = () => {
  getCourseInfoPage()
}
const handleCurrentChange = () => {
  getCourseInfoPage()
}
</script>
<style scoped lang="scss">
.course_box {
  padding: 24px;

  .course_addbtn {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
  }
}
</style>
